// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MatrixFramework.Keycloak.Abstractions.Models;
using MatrixFramework.Keycloak.Abstractions.Options;

namespace MatrixFramework.Keycloak.Services;

/// <summary>
/// KeycloakAdminService性能优化扩展
/// </summary>
public static class KeycloakAdminServicePerformanceOptimizations
{
    /// <summary>
    /// 获取缓存的服务器信息
    /// </summary>
    /// <param name="service">KeycloakAdminService实例</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>服务器信息</returns>
    public static async Task<MatrixFramework.Core.Results.Result<ServerInfo>> GetServerInfoCachedAsync(
        this KeycloakAdminService service,
        CancellationToken cancellationToken = default)
    {
        // 使用缓存键
        var cacheKey = $"Keycloak_ServerInfo_{service.Options.BaseUrl}";

        // 这里需要在实际实现中添加缓存逻辑
        // 目前返回基本的服务器信息调用
        return await service.GetServerInfoAsync(cancellationToken);
    }

    /// <summary>
    /// 清除Keycloak缓存
    /// </summary>
    /// <param name="service">KeycloakAdminService实例</param>
    /// <param name="keyPattern">缓存键模式</param>
    public static void ClearCache(this KeycloakAdminService service, string? keyPattern = null)
    {
        // 在实际实现中，这里会清除IMemoryCache中的缓存项
        // 目前为占位符实现
    }

    /// <summary>
    /// 创建带性能优化的HTTP客户端工厂
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="options">配置选项</param>
    /// <returns>服务集合</returns>
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddOptimizedKeycloakHttpClient(
        this Microsoft.Extensions.DependencyInjection.IServiceCollection services,
        KeycloakOptions options)
    {
        // 配置优化的HTTP客户端
        services.AddHttpClient("KeycloakAdmin", client =>
        {
            client.BaseAddress = new System.Uri(options.BaseUrl);
            client.Timeout = System.TimeSpan.FromSeconds(options.TimeoutSeconds);

            // 配置重试机制
            client.DefaultRequestHeaders.Add("User-Agent", options.HttpClient.UserAgent);

            // 启用HTTP/2
            // Note: HttpClientOptions.EnableHttp2 not available in this version
            client.DefaultRequestVersion = System.Net.HttpVersion.Version20;
        });

        return services;
    }

    /// <summary>
    /// 配置内存缓存选项
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <returns>服务集合</returns>
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection ConfigureOptimizedMemoryCache(
        this Microsoft.Extensions.DependencyInjection.IServiceCollection services)
    {
        services.AddMemoryCache(options =>
        {
            // 设置缓存大小限制
            options.SizeLimit = 1024 * 1024 * 100; // 100MB

            // 设置压缩阈值
            options.CompactionPercentage = 0.05;

            // 设置滑动过期时间
            options.ExpirationScanFrequency = System.TimeSpan.FromMinutes(1);
        });

        return services;
    }
}

/// <summary>
/// 性能监控指标
/// </summary>
public class PerformanceMetrics
{
    /// <summary>
    /// 总请求数
    /// </summary>
    public long TotalRequests { get; set; }

    /// <summary>
    /// 成功请求数
    /// </summary>
    public long SuccessfulRequests { get; set; }

    /// <summary>
    /// 平均响应时间（毫秒）
    /// </summary>
    public double AverageResponseTimeMs { get; set; }

    /// <summary>
    /// 缓存命中数
    /// </summary>
    public long CacheHits { get; set; }

    /// <summary>
    /// 并发请求数
    /// </summary>
    public int ConcurrentRequests { get; set; }

    /// <summary>
    /// 错误率（百分比）
    /// </summary>
    public double ErrorRate => TotalRequests > 0 ? (double)(TotalRequests - SuccessfulRequests) / TotalRequests * 100 : 0;

    /// <summary>
    /// 缓存命中率（百分比）
    /// </summary>
    public double CacheHitRate => TotalRequests > 0 ? (double)CacheHits / TotalRequests * 100 : 0;
}

/// <summary>
/// 缓存配置选项
/// </summary>
public class CacheConfiguration
{
    /// <summary>
    /// 默认过期时间
    /// </summary>
    public System.TimeSpan DefaultExpiration { get; set; } = System.TimeSpan.FromMinutes(5);

    /// <summary>
    /// 服务器信息缓存过期时间
    /// </summary>
    public System.TimeSpan ServerInfoExpiration { get; set; } = System.TimeSpan.FromMinutes(10);

    /// <summary>
    /// 用户信息缓存过期时间
    /// </summary>
    public System.TimeSpan UserInfoExpiration { get; set; } = System.TimeSpan.FromMinutes(15);

    /// <summary>
    /// 角色信息缓存过期时间
    /// </summary>
    public System.TimeSpan RoleInfoExpiration { get; set; } = System.TimeSpan.FromMinutes(30);

    /// <summary>
    /// 是否启用缓存
    /// </summary>
    public bool Enabled { get; set; } = true;

    /// <summary>
    /// 缓存大小限制（MB）
    /// </summary>
    public long SizeLimitMB { get; set; } = 100;
}

/// <summary>
/// HTTP客户端配置选项
/// </summary>
public class HttpClientConfiguration
{
    /// <summary>
    /// 默认超时时间（秒）
    /// </summary>
    public int DefaultTimeoutSeconds { get; set; } = 30;

    /// <summary>
    /// 最大并发连接数
    /// </summary>
    public int MaxConcurrentConnections { get; set; } = 100;

    /// <summary>
    /// 连接超时时间（秒）
    /// </summary>
    public int ConnectTimeoutSeconds { get; set; } = 10;

    /// <summary>
    /// 读取超时时间（秒）
    /// </summary>
    public int ReadTimeoutSeconds { get; set; } = 30;

    /// <summary>
    /// 启用HTTP/2
    /// </summary>
    public bool EnableHttp2 { get; set; } = true;

    /// <summary>
    /// 启用自动重试
    /// </summary>
    public bool EnableRetry { get; set; } = true;

    /// <summary>
    /// 重试次数
    /// </summary>
    public int RetryCount { get; set; } = 3;

    /// <summary>
    /// 重试延迟（毫秒）
    /// </summary>
    public int RetryDelayMs { get; set; } = 1000;
}